
/**   
 * @Title: FileUtil.java 
 * @Package: com.rename.icode.utils 
 * @Description: Administrator版权所有
 * @author Administrator  
 * @date 2015-2-11 下午4:41:14 
 * @version  
 */


package com.rename.icode.utils;

import android.R.string;
import android.annotation.TargetApi;
import android.content.BroadcastReceiver;
import android.content.ContentUris;
import android.content.Context;
import android.database.Cursor;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.net.Uri;
import android.os.Build;
import android.os.Environment;
import android.os.StatFs;
import android.provider.DocumentsContract;
import android.provider.MediaStore;

import com.rename.icode.comm.Constants;

import org.apache.http.conn.util.InetAddressUtils;

import java.io.BufferedInputStream;
import java.io.BufferedReader;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.FileReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.LineNumberReader;
import java.io.OutputStream;
import java.io.Reader;
import java.math.BigDecimal;
import java.net.InetAddress;
import java.net.NetworkInterface;
import java.net.SocketException;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.util.ArrayList;
import java.util.Enumeration;
import java.util.List;

/** 
 * @Description 实现了...功能
 * @author Administrator
 * @date 2015-2-11 下午4:41:14 
 * @version V1.0
 */

public class FileUtil {
	private static final String TAG = "FileUtil";

	// 通过uri获取手机中的资源文件
	@TargetApi(Build.VERSION_CODES.KITKAT)
	public static String getPath2(final Context context, final Uri uri) {

		final boolean isKitKat = Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT;

		// DocumentProvider
		if (isKitKat && DocumentsContract.isDocumentUri(context, uri)) {
			// ExternalStorageProvider
			if (isExternalStorageDocument(uri)) {
				LogUtil.i(TAG, "isExternalStorageDocument");
				final String docId = DocumentsContract.getDocumentId(uri);
				final String[] split = docId.split(":");
				final String type = split[0];

				if ("primary".equalsIgnoreCase(type)) {
					return Environment.getExternalStorageDirectory() + "/"
							+ split[1];
				}

				// TODO handle non-primary volumes
			}
			// DownloadsProvider
			else if (isDownloadsDocument(uri)) {

				LogUtil.i(TAG, "isDownloadsDocument");
				final String id = DocumentsContract.getDocumentId(uri);
				final Uri contentUri = ContentUris.withAppendedId(
						Uri.parse("content://downloads/public_downloads"),
						Long.valueOf(id));

				return getDataColumn(context, contentUri, null, null);
			}
			// MediaProvider
			else if (isMediaDocument(uri)) {
				LogUtil.i(TAG, "isMediaDocument");
				final String docId = DocumentsContract.getDocumentId(uri);
				final String[] split = docId.split(":");
				final String type = split[0];

				LogUtil.i(TAG, "docId: " + docId);
				LogUtil.i(TAG, "type: " + type);
				LogUtil.i(TAG, "split length: " + split.length);
				Uri contentUri = null;
				if ("image".equals(type)) {
					LogUtil.i(TAG, "image");
					contentUri = MediaStore.Images.Media.EXTERNAL_CONTENT_URI;
				} else if ("video".equals(type)) {
					LogUtil.i(TAG, "video");
					contentUri = MediaStore.Video.Media.EXTERNAL_CONTENT_URI;
				} else if ("audio".equals(type)) {
					LogUtil.i(TAG, "audio");
					contentUri = MediaStore.Audio.Media.EXTERNAL_CONTENT_URI;
				}

				LogUtil.i(TAG, "contentUri: " + contentUri.toString());

				final String selection = "_id=?";
				final String[] selectionArgs = new String[] { split[1] };

				return getDataColumn(context, contentUri, selection,
						selectionArgs);
			}
		}
		// MediaStore (and general)
		else if ("content".equalsIgnoreCase(uri.getScheme())) {

			LogUtil.i(TAG, "content...");
			// Return the remote address
			if (isGooglePhotosUri(uri))
				return uri.getLastPathSegment();

			LogUtil.i(TAG, "normal...");
			LogUtil.i(TAG, "contentUri: " + uri.toString());

			return getDataColumn(context, uri, null, null);
		}
		// File
		else if ("file".equalsIgnoreCase(uri.getScheme())) {
			LogUtil.i(TAG, "file...");

			return uri.getPath();
		}

		return null;
	}

	/**
	 * Get the value of the data column for this Uri. This is useful for
	 * MediaStore Uris, and other file-based ContentProviders.
	 * 
	 * @param context
	 *            The context.
	 * @param uri
	 *            The Uri to query.
	 * @param selection
	 *            (Optional) Filter used in the query.
	 * @param selectionArgs
	 *            (Optional) Selection arguments used in the query.
	 * @return The value of the _data column, which is typically a file path.
	 */
	public static String getDataColumn(Context context, Uri uri,
			String selection, String[] selectionArgs) {

		Cursor cursor = null;
		final String column = "_data";
		final String[] projection = { column };

		try {
			cursor = context.getContentResolver().query(uri, projection,
					selection, selectionArgs, null);
			if (cursor != null && cursor.moveToFirst()) {
				final int index = cursor.getColumnIndexOrThrow(column);
				LogUtil.i(TAG,
						"cursor.getString(index): " + cursor.getString(index));
				return cursor.getString(index);
			}
		} finally {
			if (cursor != null)
				cursor.close();
		}
		return null;
	}

	/**
	 * @param uri
	 *            The Uri to check.
	 * @return Whether the Uri authority is ExternalStorageProvider.
	 */
	public static boolean isExternalStorageDocument(Uri uri) {
		return "com.android.externalstorage.documents".equals(uri
				.getAuthority());
	}

	/**
	 * @param uri
	 *            The Uri to check.
	 * @return Whether the Uri authority is DownloadsProvider.
	 */
	public static boolean isDownloadsDocument(Uri uri) {
		return "com.android.providers.downloads.documents".equals(uri
				.getAuthority());
	}

	/**
	 * @param uri
	 *            The Uri to check.
	 * @return Whether the Uri authority is MediaProvider.
	 */
	public static boolean isMediaDocument(Uri uri) {
		return "com.android.providers.media.documents".equals(uri
				.getAuthority());
	}

	/**
	 * @param uri
	 *            The Uri to check.
	 * @return Whether the Uri authority is Google Photos.
	 */
	public static boolean isGooglePhotosUri(Uri uri) {
		return "com.google.android.apps.photos.content".equals(uri
				.getAuthority());
	}

//	public static String getPath(Context context, Uri uri) {
//
//		if ("content".equalsIgnoreCase(uri.getScheme())) {
//			String[] projection = { "_data" };
//			Cursor cursor = null;
//
//			try {
//				cursor = context.getContentResolver().query(uri, projection,
//						null, null, null);
//				int column_index = cursor.getColumnIndexOrThrow("_data");
//				if (cursor.moveToFirst()) {
//					return cursor.getString(column_index);
//				}
//			} catch (Exception e) {
//				// Eat it
//			}
//		}
//
//		else if ("file".equalsIgnoreCase(uri.getScheme())) {
//			return uri.getPath();
//		}
//
//		return null;
//	}

	/**
	 * 计算文件大小
	 * 
	 * @param size
	 * @return
	 */
	public static String getFormatSize(double size) {
		double kiloByte = size / 1024;
		if (kiloByte < 1) {
			return size + "Byte(s)";
		}

		double megaByte = kiloByte / 1024;
		if (megaByte < 1) {
			BigDecimal result1 = new BigDecimal(Double.toString(kiloByte));
			return result1.setScale(2, BigDecimal.ROUND_HALF_UP)
					.toPlainString() + "KB";
		}

		double gigaByte = megaByte / 1024;
		if (gigaByte < 1) {
			BigDecimal result2 = new BigDecimal(Double.toString(megaByte));
			return result2.setScale(2, BigDecimal.ROUND_HALF_UP)
					.toPlainString() + "MB";
		}

		double teraBytes = gigaByte / 1024;
		if (teraBytes < 1) {
			BigDecimal result3 = new BigDecimal(Double.toString(gigaByte));
			return result3.setScale(2, BigDecimal.ROUND_HALF_UP)
					.toPlainString() + "GB";
		}
		BigDecimal result4 = new BigDecimal(teraBytes);
		return result4.setScale(2, BigDecimal.ROUND_HALF_UP).toPlainString()
				+ "TB";
	}

	/**
	 * 获取本机ip地址
	 * 
	 * @author wangzheng
	 * @return
	 */
	public static String getLocalHostIp() {
		String ipaddress = "";
		try {
			Enumeration<NetworkInterface> en = NetworkInterface
					.getNetworkInterfaces();
			// 遍历所用的网络接口
			while (en.hasMoreElements()) {
				NetworkInterface nif = en.nextElement();// 得到每一个网络接口绑定的所有ip
				Enumeration<InetAddress> inet = nif.getInetAddresses();
				// 遍历每一个接口绑定的所有ip
				while (inet.hasMoreElements()) {
					InetAddress ip = inet.nextElement();
					if (!ip.isLoopbackAddress()
							&& InetAddressUtils.isIPv4Address(ip
									.getHostAddress())) {
						return ipaddress = ip.getHostAddress();
					}
				}

			}
		} catch (SocketException e) {

			System.out.println("获取IP地址失败");
			e.printStackTrace();
		}
		return ipaddress;

	}

	/**
	 * 锟斤拷锟斤拷锟侥硷拷
	 * 
	 * @param fromFile
	 * @param toFile
	 * @throws IOException
	 */
	public static void copyFile(File fromFile, String toFile)
			throws IOException {

		FileInputStream from = null;
		FileOutputStream to = null;
		try {
			from = new FileInputStream(fromFile);
			to = new FileOutputStream(toFile);
			byte[] buffer = new byte[1024];
			int bytesRead;

			while ((bytesRead = from.read(buffer)) != -1)
				to.write(buffer, 0, bytesRead); // write
		} finally {
			if (from != null)
				try {
					from.close();
				} catch (IOException e) {
					LogUtil.e(TAG, "", e);
				}
			if (to != null)
				try {
					to.close();
				} catch (IOException e) {
					LogUtil.e(TAG, "", e);
				}
		}
	}

	/**
	 * 锟斤拷锟斤拷锟侥硷拷
	 * 
	 * @param file
	 * @return
	 */
	public static File createNewFile(File file) {

		try {

			if (file.exists()) {
				return file;
			}

			File dir = file.getParentFile();
			if (!dir.exists()) {
				dir.mkdirs();
			}
			if (!file.exists()) {
				file.createNewFile();
			}
		} catch (IOException e) {
			LogUtil.e(TAG, "", e);
			return null;
		}
		return file;
	}

	/**
	 * 锟斤拷锟斤拷锟侥硷拷
	 * 
	 * @param path
	 */
	public static File createNewFile(String path) {
		File file = new File(path);
		return createNewFile(file);
	}// end method createText()

	/**
	 * 删锟斤拷锟侥硷拷
	 * 
	 * @param path
	 */
	public static void deleteFile(String path) {
		File file = new File(path);
		deleteFile(file);
	}

	/**
	 * 删锟斤拷锟侥硷拷
	 * 
	 * @param file
	 */
	public static void deleteFile(File file) {
		LogUtil.i("liutaotest", "delete :" + file.toString());
		if (!file.exists()) {
			return;
		}
		if (file.isFile()) {
			file.delete();
		} else if (file.isDirectory()) {
			File files[] = file.listFiles();
			for (int i = 0; i < files.length; i++) {
				deleteFile(files[i]);
			}
		}
		file.delete();
	}

	/**
	 * 锟斤拷Text锟侥硷拷锟斤拷写锟斤拷锟斤拷锟斤拷
	 * 
	 * @param file
	 * @param content
	 * @return
	 */
	public static boolean write(String path, String content) {
		return write(path, content, false);
	}

	public static boolean write(String path, String content, boolean append) {
		return write(new File(path), content, append);
	}

	public static boolean write(File file, String content) {
		return write(file, content, false);
	}

	public static boolean write(File file, String content, boolean append) {
		if (file == null || StringUtil.empty(content)) {
			return false;
		}
		if (!file.exists()) {
			file = createNewFile(file);
		}
		FileOutputStream ops = null;
		try {
			ops = new FileOutputStream(file, append);
			ops.write(content.getBytes());
			ops.flush();
		} catch (Exception e) {
			LogUtil.e(TAG, "", e);
			return false;
		} finally {
			try {
				ops.close();
			} catch (IOException e) {
				LogUtil.e(TAG, "", e);
			}
			ops = null;
		}

		return true;
	}

	/**
	 * 锟斤拷锟斤拷募锟斤拷锟�
	 * 
	 * @param path
	 * @return
	 */
	public static String getFileName(String path) {
		if (StringUtil.empty(path)) {
			return null;
		}
		File f = new File(path);
		String name = f.getName();
		f = null;
		return name;
	}

	/**
	 * 
	 * @Description 从sd卡中读取文件并转为输入流
	 * @author WangXinMing
	 * @param file
	 * @return
	 */
	public static InputStream readFileFromSDCard(File file) {
		InputStream is = null;
		LogUtil.i(TAG, "sdcard state: " + Environment.getExternalStorageState());
		if (Environment.getExternalStorageState().equals(
				Environment.MEDIA_MOUNTED)) {
			System.out.println("file" + file.getAbsolutePath().toString()
					+ ",length: " + file.length());
			try {
				is = new FileInputStream(file);
				System.out.println("is : " + (is == null));
				return is;
			} catch (FileNotFoundException e) {
				System.out.println(e.toString());
				System.out.println("is : " + (is == null));
				e.printStackTrace();
			}
		}
		return is;
	}

	/**
	 * 
	 * @Description 读取文件内容转为字符串
	 * @author WangXinMing
	 * @param path
	 * @return
	 */
	public static String readFileToString(String path) {
		File file = new File(path);
		LogUtil.i(TAG, "path: " + path);
		if (file.exists()) {
			InputStream is = readFileFromSDCard(file);
			ByteArrayOutputStream outStream = new ByteArrayOutputStream();
			byte[] buffer = new byte[1024];
			int len = 0;
			try {
				while ((len = is.read(buffer)) != -1) {
					outStream.write(buffer, 0, len);
				}
				byte[] temp = outStream.toByteArray();
				String str = new String(temp, "GBK");
				LogUtil.i(TAG, "file to string : " + str);
				is.close();
				return str;
			} catch (IOException e) {
				e.printStackTrace();
			}
		}

		return null;
	}

	/**
	 * 
	 * @Description 获取文件列表
	 * @author Administrator
	 * @param fileDir
	 * @return
	 */
	public static File[] getFiles(String fileDir){
		File[] files = null;
		if(isFileExist(fileDir)){
			File file = new File(fileDir);
			files = file.listFiles();
		}
		
		return files;
	}
	
	public static Bitmap readPicFromSDCard(String path) {
		File file = new File(path);
		LogUtil.i(TAG, "btimap path: " + path);
		LogUtil.i(TAG, "Bitmap file exists: " + file.exists());
		if (file.exists()) {
			Bitmap bitmap = BitmapFactory.decodeFile(path);
			LogUtil.i(TAG, "bitmap is null?: " + (bitmap == null));
			return bitmap;
		}
		return null;
	}

	public static byte[] toByteArray(String filename) throws IOException {

		File f = new File(filename);
		if (!f.exists()) {
			throw new FileNotFoundException(filename);
		}

		ByteArrayOutputStream bos = new ByteArrayOutputStream((int) f.length());
		BufferedInputStream in = null;
		try {
			in = new BufferedInputStream(new FileInputStream(f));
			int buf_size = 1024;
			byte[] buffer = new byte[buf_size];
			int len = 0;
			while (-1 != (len = in.read(buffer, 0, buf_size))) {
				bos.write(buffer, 0, len);
			}
			return bos.toByteArray();
		} catch (IOException e) {
			e.printStackTrace();
			throw e;
		} finally {
			try {
				in.close();
			} catch (IOException e) {
				e.printStackTrace();
			}
			bos.close();
		}
	}

	/**
	 * 锟斤拷取锟侥硷拷锟斤拷锟捷ｏ拷锟接碉拷startLine锟叫匡拷始锟斤拷锟斤拷取lineCount锟斤拷
	 * 
	 * @param file
	 * @param startLine
	 * @param lineCount
	 * @return 锟斤拷锟斤拷锟斤拷锟街碉拷list,锟斤拷锟�list.size<lineCount锟斤拷说锟斤拷锟斤拷锟斤拷锟侥硷拷末尾锟斤拷
	 */
	@SuppressWarnings("resource")
	public static List<String> readFile(File file, int startLine, int lineCount) {
		if (file == null || startLine < 1 || lineCount < 1) {
			return null;
		}
		if (!file.exists()) {
			return null;
		}
		FileReader fileReader = null;
		List<String> list = null;
		try {
			list = new ArrayList<String>();
			fileReader = new FileReader(file);
			LineNumberReader lnr = new LineNumberReader(fileReader);
			boolean end = false;
			for (int i = 1; i < startLine; i++) {
				if (lnr.readLine() == null) {
					end = true;
					break;
				}
			}
			if (end == false) {
				for (int i = startLine; i < startLine + lineCount; i++) {
					String line = lnr.readLine();
					if (line == null) {
						break;
					}
					list.add(line);

				}
			}
		} catch (Exception e) {
			LogUtil.e(TAG, "read log error!", e);
		} finally {
			if (fileReader != null) {
				try {
					fileReader.close();
				} catch (IOException e) {
					e.printStackTrace();
				}
			}
		}
		return list;
	}

	/**
	 * 锟斤拷锟斤拷锟侥硷拷锟斤拷
	 * 
	 * @param dir
	 * @return
	 */
	public static boolean createDir(File dir) {
		try {
			if (!dir.exists()) {
				dir.mkdirs();
			}
			return true;
		} catch (Exception e) {
			LogUtil.e(TAG, "create dir error", e);
			return false;
		}
	}

	/**
	 * 锟斤拷SD锟斤拷锟较达拷锟斤拷目录
	 * 
	 * @param dirName
	 */
	public static File creatSDDir(String dirName) {
		File dir = new File(dirName);
		dir.mkdir();
		return dir;
	}

	/**
	 * 锟叫讹拷SD锟斤拷锟较碉拷锟侥硷拷锟角凤拷锟斤拷锟�
	 */
	public static boolean isFileExist(String fileName) {
		File file = new File(fileName);
		return file.exists();
	}

	/**
	 * 锟斤拷一锟斤拷InputStream锟斤拷锟斤拷锟斤拷锟斤拷锟叫达拷氲�SD锟斤拷锟斤拷
	 */
	public static File write2SDFromInput(String path, String fileName,
			InputStream input) {
		File file = null;
		OutputStream output = null;
		try {
			creatSDDir(path);
			file = createNewFile(path + "/" + fileName);
			output = new FileOutputStream(file);
			byte buffer[] = new byte[1024];
			int len = -1;
			while ((len = input.read(buffer)) != -1) {
				output.write(buffer, 0, len);
			}
			output.flush();
		} catch (Exception e) {
			e.printStackTrace();
		} finally {
			try {
				output.close();
			} catch (Exception e) {
				e.printStackTrace();
			}
		}
		return file;
	}

	// 锟斤拷锟侥硷拷锟斤拷一锟斤拷一锟叫的讹拷取锟侥硷拷
	public static String readFile(File file) {
		Reader read = null;
		String content = "";
		String string = "";
		BufferedReader br = null;
		try {
			read = new FileReader(file);
			br = new BufferedReader(read);
			while ((content = br.readLine()) != null) {
				string += content.trim() + "\r\n";
			}
		} catch (Exception e) {
			e.printStackTrace();
		} finally {
			try {
				read.close();
				br.close();
			} catch (Exception e) {
				e.printStackTrace();
			}
		}
		System.out.println("string=" + string);
		return string.toString();
	}
	
	/**
	 * 
	 * @Description 读取文件内容转换成字符串，使用List存储
	 * @author Administrator
	 * @param file
	 * @return
	 */
	public static List<String> readFileToStrings(File file) {
		Reader read = null;
		String content = "";
		String string = "";
		List<String> strings = null;
		BufferedReader br = null;
		try {
			read = new FileReader(file);
			br = new BufferedReader(read);
			strings = new ArrayList<String>();
			while ((content = br.readLine()) != null) {
				string += content.trim() + "\r\n";
				strings.add(content.trim());
				LogUtil.i("wxm", "文件中的一行" + content.trim());
			}
		} catch (Exception e) {
			e.printStackTrace();
		} finally {
			try {
				read.close();
				br.close();
			} catch (Exception e) {
				e.printStackTrace();
			}
		}
		System.out.println("string=" + string);
		return strings;
	}

	public static String readFileCompact(File file) {
		Reader read = null;
		String content = "";
		String string = "";
		BufferedReader br = null;
		try {
			read = new FileReader(file);
			br = new BufferedReader(read);
			while ((content = br.readLine()) != null) {
				string += content.trim();
			}
		} catch (Exception e) {
			e.printStackTrace();
		} finally {
			try {
				read.close();
				br.close();
			} catch (Exception e) {
				e.printStackTrace();
			}
		}
		System.out.println("string=" + string);
		return string.toString();
	}

//	public static List<String> getEmojiFile() {
//		try {
//			List<String> list = new ArrayList<String>();
//			InputStream in = ApplicationContext.get().getResources()
//					.getAssets().open("emoji");
//			BufferedReader br = new BufferedReader(new InputStreamReader(in,
//					"UTF-8"));
//			String str = null;
//			while ((str = br.readLine()) != null) {
//				list.add(str);
//			}
//
//			return list;
//		} catch (IOException e) {
//			e.printStackTrace();
//		}
//		return null;
//	}

	public static String getAKeyDeviceInfo() {

		String cmd = "cat /proc/bus/usb/devices";
		LogUtil.d(TAG, cmd);

		Runtime run = Runtime.getRuntime();
		try {
			Process p = run.exec(cmd);
			BufferedInputStream in = new BufferedInputStream(p.getInputStream());
			BufferedReader inBr = new BufferedReader(new InputStreamReader(in));

			String lineStr;
			while ((lineStr = inBr.readLine()) != null) {
				// 锟斤拷锟斤拷锟斤拷锟街达拷泻锟斤拷诳锟斤拷锟教�锟斤拷锟斤拷锟斤拷锟较�
				LogUtil.d(TAG, lineStr);
				// if (lineStr.contains("usb") || lineStr.contains("udisk")) {
				// String[] strArray = lineStr.split(" ");
				// if (strArray != null && strArray.length >= 3) {
				// String result = strArray[1].trim();
				// return result;
				// }
				// }
				// 锟斤拷锟斤拷锟斤拷锟斤拷欠锟街达拷锟绞э拷堋锟�
				if (p.waitFor() != 0 && p.exitValue() == 1) {
					// p.exitValue()==0锟斤拷示锟斤拷锟斤拷锟斤拷锟斤拷锟斤拷1锟斤拷锟斤拷锟斤拷锟斤拷锟斤拷锟斤拷
					LogUtil.e(TAG, "check mount info failed");
					return null;
				}
			}
			inBr.close();
			in.close();
		} catch (Exception e) {
			e.printStackTrace();
			return null;
		}

		return null;
	}

	public static String getAKeyPath() {

		String cmd = "cat /proc/mounts";
		LogUtil.d(TAG, cmd);

		Runtime run = Runtime.getRuntime();
		try {
			Process p = run.exec(cmd);
			BufferedInputStream in = new BufferedInputStream(p.getInputStream());
			BufferedReader inBr = new BufferedReader(new InputStreamReader(in));

			String lineStr;
			while ((lineStr = inBr.readLine()) != null) {
				// 锟斤拷锟斤拷锟斤拷锟街达拷泻锟斤拷诳锟斤拷锟教�锟斤拷锟斤拷锟斤拷锟较�
				LogUtil.d(TAG, lineStr);
				if (lineStr.toLowerCase().contains("usb")
						|| lineStr.toLowerCase().contains("udisk")) {
					String[] strArray = lineStr.split(" ");
					if (strArray != null && strArray.length >= 3) {
						String result = strArray[1].trim();
						return result;
					}
				}
				// 锟斤拷锟斤拷锟斤拷锟斤拷欠锟街达拷锟绞э拷堋锟�
				if (p.waitFor() != 0 && p.exitValue() == 1) {
					// p.exitValue()==0锟斤拷示锟斤拷锟斤拷锟斤拷锟斤拷锟斤拷1锟斤拷锟斤拷锟斤拷锟斤拷锟斤拷锟斤拷
					LogUtil.e(TAG, "check mount info failed");
					return null;
				}
			}
			inBr.close();
			in.close();
		} catch (Exception e) {
			e.printStackTrace();
			return null;
		}

		return null;
	}

	public static String getSDCardRootDirectory() {

		if (Environment.MEDIA_MOUNTED.equals(Environment
				.getExternalStorageState())) {
			return Environment.getExternalStorageDirectory().getAbsolutePath();
		}

		String cmd = "cat /proc/mounts";
		Runtime run = Runtime.getRuntime();
		try {
			Process p = run.exec(cmd);
			BufferedInputStream in = new BufferedInputStream(p.getInputStream());
			BufferedReader inBr = new BufferedReader(new InputStreamReader(in));

			String lineStr;
			while ((lineStr = inBr.readLine()) != null) {
				LogUtil.d(TAG, lineStr);
				if (lineStr.contains("sdcard")) {
					String[] strArray = lineStr.split(" ");
					if (strArray != null && strArray.length >= 3) {
						String result = strArray[1].trim();
						return result;
					}
				}
				if (p.waitFor() != 0 && p.exitValue() == 1) {
					LogUtil.e(TAG, "check mount info failed");
					return null;
				}
			}
			inBr.close();
			in.close();
		} catch (Exception e) {
			e.printStackTrace();
			return null;
		}

		return null;
	}

	@SuppressWarnings("deprecation")
	public static boolean checkPathValid(String path) {
		StatFs s = null;
		try {
			s = new StatFs(path);
		} catch (Exception e) {
			e.printStackTrace();
			return false;
		}

		if (s.getBlockCount() * s.getBlockSize() != 0) {
			return true;
		} else {
			return false;
		}
	}

	@SuppressWarnings("resource")
	public static boolean checkFileValid(String path, String size, String sha1) {
		File downloadFile = new File(path);

		if (downloadFile.length() == Long.parseLong(size)) {
			StringBuffer hexString = new StringBuffer();

			try {
				MessageDigest md = MessageDigest.getInstance("SHA-1");
				FileInputStream fis = new FileInputStream(path);
				byte[] dataBytes = new byte[4096];
				int nread = 0;
				while ((nread = fis.read(dataBytes)) != -1) {
					md.update(dataBytes, 0, nread);
				}
				byte[] mdbytes = md.digest();

				for (int i = 0; i < mdbytes.length; i++) {
					hexString.append(Integer.toString(
							(mdbytes[i] & 0xff) + 0x100, 16).substring(1));
				}
				// compare with sha hash code
				LogUtil.d(TAG, "rule SHA-1: " + hexString.toString()
						+ ", download SHA1 = " + sha1);

			} catch (NoSuchAlgorithmException e) {
				LogUtil.e(TAG, "There is no SHA-1 algorithm");
				e.printStackTrace();
			} catch (FileNotFoundException e) {
				LogUtil.e(TAG, "Update package does not exists");
				e.printStackTrace();
			} catch (IOException e) {
				LogUtil.e(TAG, "Read file error. Maybe file is corrupted");
				e.printStackTrace();
			}

			if (sha1 != null && sha1.equalsIgnoreCase(hexString.toString())) {
				return true;
			} else {
				return false;
			}
		} else {
			LogUtil.e(TAG, "rule size: " + size + ", download size = "
					+ downloadFile.length());

			return false;
		}
	}

	public static String getGlobalLogPath() {
		if (Constants.SDCARD_ROOT_PATH == null) {
			return null;
		}
		return Constants.SDCARD_ROOT_PATH + Constants.LOG_PATH + File.separator;
	}

	public static String getGlobalCachePath() {
		if (Constants.SDCARD_ROOT_PATH == null) {
			return null;
		}

		return Constants.SDCARD_ROOT_PATH + Constants.CACHE_PATH + File.separator;
	}
	
	public static String getGlobalCodePath(){
		if (Constants.SDCARD_ROOT_PATH == null) {
			return null;
		}

		return Constants.SDCARD_ROOT_PATH + Constants.CODE_PATH + File.separator;
	}

	public static String genLogFileName() {
		return Constants.LOG_PREFIX + "-"
				+ DateUtil.getCurDateStr("yyyy-MM-dd-HH-mm-ss") + ".log";
	}

}
